package org.bes.WinClass;

import org.bes.utils.StrPathUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.bes.WinClass.VersionControl.versionFileMap;
import static org.bes.utils.StrPathUtils.VERSION_PATTERN;


public class FileManager {

    public static final String BACKUP_NAME = "backup";
    public static final String TMP = "tmp";
    public static final String VERSION_FILE = "version.json";
    public static final String PATCH_FOLDER = "patch";
    public static final String JAR_EXTRACT = "tmpJarExtract";
    public static final String JSON_DELETE = "ToDelete.json";



    public static String version;

    public static Path sourceDir;    //source path for the file to be patched
    public static Path tmpDir;
    public static Path backupDir;
    public static Path patchParentDir;
    public static Path patchUnzipDir;
    public static Path patchFilePath;
    public static Path tmpJarExtractDir;

    //public static List<File> fileList = new ArrayList<>(); // save the files extracted from the patch file
    //public static Map<String, File> fileListMap = new TreeMap<>();
    public static Queue<Map.Entry<String, File>> fileListQueue = new LinkedList<>();
    public static Queue<Map.Entry<String, File>> updateFileQueue = new LinkedList<>();
    // List to hold folder names with V+number pattern
    // 存储已经升级更新的文件的相对路径
    public static Set<Path> upgradedFilePaths = new HashSet<>();

    public static Path getTmpDir() {
        return tmpDir;
    }

    public static void setTmpDir() {
        FileManager.tmpDir = getPatchParentDir().resolve(TMP);
    }

    public static Path getPatchUnzipDir() {
        return patchUnzipDir;
    }

    public static void setPatchUnzipDir() {
        Path fileName = StrPathUtils.getFileNameWithoutExtension(patchFilePath);
        FileManager.patchUnzipDir = patchFilePath.getParent().resolve(fileName);

    }

    public static String getVersion() {
        return version;
    }

    public static void setVersion() {
        FileManager.version = String.valueOf(getPatchUnzipDir());
    }

    public FileManager(Path patchFilePath) throws IOException {
        setPatchFilePath(patchFilePath);

        setSourceDir();
        setPatchUnzipDir();
        setVersion();
        setPatchParentDir(patchFilePath);
        setPatchFilePath(patchFilePath);
        setBackupDir();
        setTmpDir();
        setTmpJarExtractDir();
    }

    public static Path getTmpJarExtractDir() {
        return tmpJarExtractDir;
    }

    public static void setTmpJarExtractDir() throws IOException {
        FileManager.tmpJarExtractDir = getPatchParentDir().resolve(JAR_EXTRACT);
        Files.createDirectories(FileManager.tmpJarExtractDir);
    }

    public static Path getPatchParentDir() {
        return patchParentDir;
    }

    public static void setPatchParentDir(Path patchFilePath) {
        FileManager.patchParentDir = patchFilePath.getParent();
    }

    public static Path getPatchFilePath() {
        return patchFilePath;
    }

    public static void setPatchFilePath(Path patchFilePath) {
        FileManager.patchFilePath = patchFilePath;
    }


    public static Path getBackupDir() {
        return backupDir;
    }

    public static void setBackupDir() {
        FileManager.backupDir = getPatchParentDir().resolve(BACKUP_NAME);
    }



    public static Path getSourceDir() {
        return sourceDir;
    }

    public static void setSourceDir() {
        FileManager.sourceDir = patchFilePath.getParent().getParent();
    }

    public static void addVersionFileMap(File file) {
        // 获取文件的绝对路径
        String filePath = file.getAbsolutePath();

        // 使用正则匹配版本号
        Matcher matcher = VERSION_PATTERN.matcher(filePath);

        // 如果找到了匹配的版本号
        if (matcher.find()) {
            // 提取版本号（例如：V2.0.0 -> 2.0.0）
            String version = matcher.group(1);

            // 如果是普通文件，直接添加
            versionFileMap.computeIfAbsent(version, k -> new ArrayList<>()).add(file);
            System.out.println("Added file: " + file.getName() + " to version: " + version);

        } else {
            // 如果没有匹配的版本号，打印提示信息
            System.out.println("No version found in file path: " + filePath);
        }
    }


    //// 处理 JAR 文件
    //private static void processJarFile(File jarFile, String jarVersion) {
    //    // 获取 JAR 文件的路径
    //    String jarFilePath = jarFile.getAbsolutePath();
    //    JarFileInfo jarFileInfo = jarFileMap.computeIfAbsent(jarFilePath, k -> new JarFileInfo(jarFilePath));
    //
    //    // 获取 JAR 文件的内部文件，模拟此处的内容
    //    // 假设我们获取 JAR 内的文件和版本号
    //    // 这里应该有获取 JAR 内部文件的逻辑（省略具体实现）
    //    // 假设这些文件路径是 "org/example/Main.class" 和 "com/utils/Helper.class"
    //    Map<String, String> jarContentFiles = new HashMap<>();
    //    jarContentFiles.put("org/example/Main.class", "1.0.0");
    //    jarContentFiles.put("com/utils/Helper.class", "1.0.0");
    //
    //    // 将 JAR 文件内的文件及其版本信息加入到 JAR 文件的内容中
    //    jarContentFiles.forEach((path, version) -> {
    //        jarFileInfo.contentFiles.put(path, version);
    //        jarFileInfo.updateMaxVersion(version);
    //    });
    //
    //    // 更新 JAR 文件的版本（根据内部文件的最大版本）
    //    jarFileMap.put(jarFilePath, jarFileInfo);
    //
    //    // 将 JAR 文件的路径及其内部文件的版本信息添加到 versionFileMap 中
    //    versionFileMap.computeIfAbsent(jarFileInfo.maxVersion, k -> new ArrayList<>()).add(new File(jarFilePath));
    //
    //    System.out.println("Added JAR file: " + jarFile.getName() + " with max version: " + jarFileInfo.maxVersion);
    //}
}
